package com.enzoism.springboot.dive;

import com.enzoism.springboot.dive.dao.RegionDao;
import com.enzoism.springboot.dive.model.Region;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RegionSimpleService {
    @Autowired
    private RegionDao regionDao;

    /**
     * 数据库查询
     */
    public List<Region> selectRegionList(Region region) {
        return regionDao.selectRegionList();
    }

    /**
     * 进行对象树转化（已经明确了要遍历的次数）
     */
    public List<Region> buildAreaTree(List<Region> regions) {
        // 获取第一级对象结构
        List<Region> firstLevels = regions.stream().filter(item -> item.getPid() == 0).collect(Collectors.toList());
        // 剩余的数据转化为Map
        List<Region> firstLevelRemains = new ArrayList<>(CollectionUtils.subtract(regions, firstLevels));
        Map<Integer, List<Region>> remainDataMap = firstLevelRemains.stream().collect(Collectors.groupingBy(Region::getPid));
        // 进行对象树转化
        List<Region> tree = getTreeDataInfo(firstLevels, remainDataMap);
        return tree;
    }

    /**
     * 进行对象树转化
     */
    private List<Region> getTreeDataInfo(List<Region> firstLevels, Map<Integer, List<Region>> remainDataMap) {
        List<Region> tree = new ArrayList<>();
        for (Iterator<Region> it = firstLevels.iterator(); it.hasNext(); ) {
            Region region = it.next();
            // 设置第二级参数
            List<Region> regions = remainDataMap.get(region.getId());
            region.setChildren(regions);
            // 设置第三级参数
            if (CollectionUtils.isNotEmpty(regions)) {
                for (int i = 0; i < regions.size(); i++) {
                    regions.get(i).setChildren(remainDataMap.get(regions.get(i).getId()));
                }
            }
            tree.add(region);
        }
        return tree;
    }

}